package com.liuwei.netty.heartbeat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.util.Random;

@Slf4j
public class NettyClient {
    public static void main(String[] args) {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            // 设置参数
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            // 添加解码器
                            pipeline.addLast(new StringDecoder());
                            // 添加解码器
                            pipeline.addLast(new StringEncoder());
                            // 添加业务处理
                            pipeline.addLast(new NettyHeartBeatClientHandler());
                        }
                    });
            log.info("客户端启动了");
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 9090).sync();
            Channel channel = channelFuture.channel();
            // 模拟发送心跳数据
            String packet = "heatbeat packet";
            // 模拟随机间隔时间等待,模拟网络抖动
            Random random = new Random();
            // 如果通道还活着
            while (channel.isActive()) {
                int num = random.nextInt(10);
//                模拟抖动
//                Thread.sleep( num * 1000);
                // 模拟超长超时
                Thread.sleep(20 * 1000);
                channel.writeAndFlush(packet);
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            group.shutdownGracefully();
        }
    }
}
